package com.flute.icrawler.policy.bdb.storage;

import java.io.File;

import com.flute.icrawler.config.CrawlConfigUtil;
import com.sleepycat.je.EnvironmentConfig;
import com.sleepycat.je.Transaction;

public class BdbStorageUtil {
	private static BdbEnvironment bdbEnvironment = null;

	static {
		initBdbEnvment();
	}

	/**
	 * 获取一个bdb storage --bdbname不能有重复，在定义时最好带上相应模块的名称eg. bdbname = "update.xxx"
	 * 
	 * @param bdbname
	 * @return
	 */
	public static IStorage getStorage(String bdbname) {
		IStorage storage = new BdbStorage(bdbname, bdbEnvironment);
		return storage;
	}

	/**
	 * 取得事务
	 * 
	 * @return
	 */
	public static Transaction beginTransaction() {
		return bdbEnvironment.beginTransaction(null, null);
	}

	/**
	 * 关闭env.
	 */
	public static void closeBdbEnvironment() {
		if (bdbEnvironment != null) {
			bdbEnvironment.close();
		}
	}

	/**
	 * 
	 *初始化bdb env
	 */
	private static void initBdbEnvment() {
		EnvironmentConfig envConfig = new EnvironmentConfig();
		envConfig.setAllowCreate(true);
		envConfig.setSharedCache(true);
		envConfig.setLocking(true);
		envConfig.setTransactional(true);
		bdbEnvironment = new BdbEnvironment(getEnvHome(), envConfig);
	}

	/**
	 * bdb envHome
	 * 
	 * @return
	 */
	private static File getEnvHome() {
		String envHome = CrawlConfigUtil.getBaseConfig().getUpdate().getBdb()
				.getEnvhome();
		if (envHome == null || envHome.trim().equals("")) {
			envHome = "bdb";
		}
		File dir = new File(envHome);
		if (!dir.exists() || !dir.isDirectory()) {
			dir.mkdirs();
		}
		return dir;
	}
}
